package cn.liwq.study.demo.netty.lab.mahjong.common.protocol;

import cn.liwq.study.demo.netty.lab.mahjong.common.enums.MessageManager;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import lombok.Data;

import java.nio.charset.StandardCharsets;

/**
 * @author lweiqiang
 * @date 2021/5/8
 */
@Data
public class MahjongProtocol {
    /** 协议头 */
    private MahjongProtocolHeader header;
    /** 协议体 */
    private MahjongProtocolBody body;

    public void encode(ByteBuf buffer) {
        // 协议头编码
        header.encode(buffer);
        // body 序列化成 json 字符串字节流
        buffer.writeBytes(JSON.toJSONString(body).getBytes(StandardCharsets.UTF_8));
    }

    public void decode(ByteBuf msg) {
        // 解码 header
        MahjongProtocolHeader header = new MahjongProtocolHeader();
        header.decode(msg);
        this.header = header;

        // 解码 body
        Class<? extends MahjongProtocolBody> bodyType = getBodyTypeByCmd(header.getCmd());
        this.body = JSON.parseObject(msg.toString(StandardCharsets.UTF_8), bodyType);
    }

    private Class<? extends MahjongProtocolBody> getBodyTypeByCmd(int cmd) {
        return MessageManager.getTypeByCmd(cmd);
    }
}
